package com.jrx.anytxn.param.transaction.job.billCompare.config;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.feign.common.GateWayPredicate;
import com.jrx.anytxn.feign.gateway.response.SmsResponse02;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransCompareDetailMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransCompareSummaryMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.transaction.config.BillCompareConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlSmsLog;
import com.jrx.anytxn.transaction.mapper.base.TlSmsLogMapper;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;


/**
 * 核心对账-对账结果发送短信job
 *
 * @author : zcc
 * 2020/11/30
 */
@Configuration
public class BillComResSendSMSConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BillComResSendSMSConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Resource
    private ExtTlBillTransCompareDetailMapper extTlBillTransCompareDetailMapper;
    @Resource
    private ExtTlBillTransCompareSummaryMapper extTlBillTransCompareSummaryMapper;
    @Autowired
    private ISegmentService iSegmentService;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IDealGatewayService dealGatewayService;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;
    @Resource
    private TlSmsLogMapper tlSmsLogMapper;
    @Autowired
    private BillCompareConfig billCompareConfig;

    @Bean
    public Job billComResSendSMSJob() {
        return jobBuilderFactory.get("billComResSendSMSJob")
                .start(billComResSendSMSStep())
                .build();
    }

    @Bean
    public Step billComResSendSMSStep() {
        return stepBuilderFactory.get("billComResSendSMSStep")
                .tasklet(billComResSendSMSTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet billComResSendSMSTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable organization = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String businessDate = DateUtils.format(organization.getToday());
            logger.info("核心放款对账-对账结果发生短信开始。。。,业务日期{}", businessDate);

            //当日交易明细不平总数
            Integer detailFailCount = extTlBillTransCompareDetailMapper
                    .countByTenantIdBusDateAndCompareStatus(organization.getTenantId(), organization.getToday(), Constant.COMPARE_FLAG_0);

            //当日交易总账不平总数
            Integer summaryFailCount = extTlBillTransCompareSummaryMapper
                    .countByTenantIdBusDateAndCompareStatus(organization.getTenantId(), organization.getToday(), Constant.COMPARE_FLAG_0);

            if(0 < detailFailCount || 0 < summaryFailCount){
                if (null != billCompareConfig.getReciveMobile()){
                    String [] reciveMobiles = billCompareConfig.getReciveMobile().split(","); //获取需要发生短信手机号
                    //循环发生短信
                    for(String reciveMobile : reciveMobiles){
                        smsSend(organization, reciveMobile);
                    }
                }
            }

            logger.info("核心放款对账-对账结果发生短信完成。。。,业务日期{}", businessDate);
            return RepeatStatus.FINISHED;
        };
    }

    private void smsSend(PrOrganizationTable organization, String mobile) throws TxnBizException {
        TlSmsLog tlSmsLog = new TlSmsLog();
        try {
            tlSmsLog.setId(iSegmentService.getId(TransBizConstant.TL_SMS_LOG_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlSmsLog.setTenantId(organization.getTenantId());
        tlSmsLog.setOrganizationId(organization.getOrganizationId());
        tlSmsLog.setCustomerId("000000");
        tlSmsLog.setProductId("000000");
        tlSmsLog.setChannel("000000");
        tlSmsLog.setMobile(mobile);
        tlSmsLog.setTemplateId("000000");
        tlSmsLog.setSmsType(TransBizConstant.SMS_TYPE_BILL_COMPARE);
        tlSmsLog.setSeqNo(SeqUtils.getSNByLength(TransBizConstant.GL_FLOW_NO_RANDOM));
        tlSmsLog.setBusinessDate(organization.getToday());
        tlSmsLog.setUpdateBy(TransBizConstant.SYS_OPRATE);
        tlSmsLog.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);

        String result = "当日对账有不平情况，请及时处理。业务日期："
                + DateUtils.format(organization.getToday()) + "。";
        tlSmsLog.setSmsContent(result);
        //直接调用网关发送短信
        try{
            //组装请求参数
            String smsRequest02Json = dealGatewayService.buildSMSRequest(tlSmsLog, result);
            GateWayPredicate<SmsResponse02> smsPre = () -> innerGatewayService.sms(smsRequest02Json);
            SmsResponse02 response = smsPre.getRes(smsPre);
            //SmsResponse02 response =  new SmsResponse02();
            if(response == null ) {
                tlSmsLog.setSendStatus(TransBizConstant.SMS_SEND_STATUS_FAIL);
            }
            tlSmsLog.setSendStatus(TransBizConstant.SMS_SEND_STATUS_SUC);
            logger.debug("短信网关返回参数：{}",response);

            //更新短信流水
            tlSmsLogMapper.insertSelective(tlSmsLog);
            logger.debug("短信流水处理完成,流水号：{}",tlSmsLog.getSeqNo());
        }catch (Exception e){
            logger.error("短信调用网关异常" ,e);
        }
    }

}
